/*
 * Copyright (C) 2020 Agrui
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include <string.h>
#include <Looper.h>
#include <Handler.h>
#include <ThreadLocal.h>


static Looper* newLooper(boolean quitAllowed) {
    Looper* looper = (Looper*)malloc(sizeof(Looper));
    if (!looper) {
        return NULL;
    }

    looper->mQueue = newMessageQueue(quitAllowed);
    if (!looper->mQueue) {
        free(looper);
        return NULL;
    }
    return looper;
}

void looperQuit(Looper* looper) {
    if (looper) {
        if (looper->mQueue) {
            deleteQueue(looper->mQueue);
            looper->mQueue = NULL;
        }
        free(looper);
    }

}

Looper* prepare(boolean quitAllowed) {
    Looper* looper;

    if (threadLocalGet() != NULL) {
        return NULL;
    }

    looper = newLooper(quitAllowed);
    if (!looper) {
        return NULL;
    }

    threadLocalSet(looper);
    return looper;
}

/**
 * Return the {@link MessageQueue} object associated with the current
 * thread.  This must be called from a thread running a Looper, or a
 * NULL point will be return.
 */
MessageQueue* myQueue() {
    Looper* looper = myLooper();
    if (!looper) {
        return NULL;
    }
    return looper->mQueue;
}


Looper* myLooper() {
    return (Looper*)threadLocalGet();
}


void loop() {
    Looper* me = myLooper();
    MessageQueue* queue;

    if (me == NULL) {
        //throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        return;
    }
    queue = me->mQueue;

    for (;;) {
        Message* msg = next(queue); // might block
        if (msg == NULL) {
            // No message indicates that the message queue is quitting.
            looperQuit(me);
            return;
        }

        dispatchMessage(msg->target, msg);
        messageRecycleUnchecked(msg);
    }
}
